package com.downguys.tool.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 
 * @author jon.liang
 * 
 */
public final class OspMessageDecoder extends ByteToMessageDecoder {
	private static final Logger logger = LoggerFactory.getLogger(OspMessageDecoder.class);

	@Override
	public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

		// length: i32
		// stx
		// data
		// etx
		if (in.readableBytes() < 5) { // length: i32
			return;
		}
		
		int begin = in.readerIndex();
		
		int length = in.readInt();
		byte b = in.readByte();
		
		if (b != 0x02) {
			logger.error("message worng STX is not 0x2: " + ctx.channel());
			ctx.close();
		}
		
		if ((in.readableBytes()+1) < length) { //因read stx, 所以报文相比length会小1, 所以需要+1
			in.readerIndex(begin);
			return;
		}
		
		in.readerIndex(begin + 4 + length);

		ByteBuf message = in.slice(begin, 4 + length); //
		message.retain();

		out.add(message);
	}

}